<script setup lang="ts">
import xsItem from "@/components/xs-item.vue";
import { getPostListApi, getCategoryListApi, readCountApi } from "@/api/post";
import { onMounted, ref } from "vue";
import * as lodash from "lodash";
import { useRouter } from "vue-router";

const router = useRouter();

const postList = ref<IPost[]>([]);

const loading = ref(false);
const finished = ref(false);

const search = ref({
  page: 1,
  limit: 10,
  categoryId: 1,
  keyword: "",
});
const total = ref(0);
const getPost = async () => {
  const res = await getPostListApi(search.value);
  postList.value = [...postList.value, ...res.data.list];
  total.value = res.data.total;

  if (postList.value.length >= total.value) {
    finished.value = true;
  } else {
    search.value.page += 1;
  }
  loading.value = false;
};

const refreshing = ref(false);
const onRefresh = async () => {
  refreshing.value = true;
  postList.value = [];
  categoryList.value = [];
  search.value.page = 1;
  await getPost();
  await getCategory();
  refreshing.value = false;
};
const categoryList = ref<ICategory[]>([]);
const getCategory = async () => {
  const res = await getCategoryListApi();
  categoryList.value = res.data;
};

const active = ref(0);
const clickTab = async (value: { title: string; name: number }) => {
  search.value.categoryId = value.name;
  search.value.page = 1;
  postList.value = [];

  await getPost();
};

const searchPost = () => {
  postList.value = [];
  search.value.page = 1;
  const debouncePost = lodash.debounce(async () => {
    await getPost();
  }, 500);
  debouncePost();
};

const toDetail = async (id: number) => {
  await readCountApi(id);
  router.push({ name: "detail", params: { id } });
};

onMounted(async () => {
  await getCategory();
});
</script>

<template>
  <div class="home">
    <van-nav-bar title="首页" />
    <form action="/">
      <van-search
        show-action
        placeholder="请输入搜索关键词"
        v-model="search.keyword"
        @update:model-value="searchPost"
      />
    </form>
    <van-tabs v-model:active="active" sticky @click-tab="clickTab">
      <van-tab
        v-for="item in categoryList"
        :title="item.name"
        :key="item.id"
        :name="item.id"
      >
        <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
          <van-list
            v-model:loading="loading"
            v-model:finished="finished"
            @load="getPost"
            finished-text="没有更多了....."
          >
            <xs-item
              :data="item"
              v-for="item in postList"
              :key="item.id"
              @click="toDetail(item.id)"
            />
          </van-list>
        </van-pull-refresh>
      </van-tab>
    </van-tabs>
  </div>
</template>
